package com.tanhua.sso.service;




import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.sso.config.HuanXinConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @program: mytanhua
 * @author: Leon
 * @date: 2021-02-20 20:17
 **/
@Service
@SuppressWarnings("all")
public class HuanXinTokenService {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private HuanXinConfig huanXinConfig;

    @Autowired
    private RestTemplate restTemplate;

    private static final String REDIS_KEY = "HUANXIN_TOKEN";

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public String getToken(){

//        先读缓存
        String cacheData = this.redisTemplate.opsForValue().get(REDIS_KEY);
        if (StringUtils.isNotEmpty(cacheData)){
            return cacheData;
        }

        String targetUrl = this.huanXinConfig.getUrl() +
                           this.huanXinConfig.getOrgName() + "/" +
                           this.huanXinConfig.getAppName() + "/token";

        Map<String,String> param = new HashMap<>();
        param.put("grant_type", "client_credentials");
        param.put("client_id", this.huanXinConfig.getClientId());
        param.put("client_secret", this.huanXinConfig.getClientSecret());

//        请求环信接口
        ResponseEntity<String> stringResponseEntity = this.restTemplate.postForEntity(targetUrl, param, String.class);

        if (stringResponseEntity.getStatusCodeValue() != 200){
            return null;
        }

        String body = stringResponseEntity.getBody();

        try {
            JsonNode jsonNode = MAPPER.readTree(body);
            String accessToken = jsonNode.get("access_token").asText();
            Long expiresIn = jsonNode.get("expires_in").asLong();
            if (StringUtils.isNotEmpty(accessToken)){
                this.redisTemplate.opsForValue().set(REDIS_KEY,accessToken,expiresIn - 86400, TimeUnit.SECONDS);
                return accessToken;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }
}
